package com.uduemc.biso.node.web.api.interceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.web.api.component.SiteHolder;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.exception.ForbiddenException;
import com.uduemc.biso.node.web.api.service.HostService;

@Component
public class ApiImageHostInterceptor implements HandlerInterceptor {

	private static final String regex = "/api/image/watermark/(\\w+)/(.*)";

	@Autowired
	private SiteHolder siteHolder;

	/**
	 * 通过 requestURI 获取 hostId 后获取对应的数据并保存至 ThreadLocal 中 并截取与站点端一致的页面URI路径后进行下一个拦截器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		HostService hostServiceImpl = SpringContextUtils.getBean("hostServiceImpl", HostService.class);

		String requestURI = request.getRequestURI();
		Pattern pattern = Pattern.compile(ApiImageHostInterceptor.regex);
		Matcher matcher = pattern.matcher(requestURI);
		if (!matcher.find()) {
			throw new ForbiddenException("pattern.matche(); 匹配失败！ requestURI: " + requestURI);
		}

		int groupCount = matcher.groupCount();
		if (groupCount != 2) {
			throw new ForbiddenException("pattern.matche(); 匹配失败！ requestURI: " + requestURI);
		}

		String enHostId = matcher.group(1);

		String deHostId = CryptoJava.de(enHostId);

		long hostId = -1;
		try {
			hostId = Long.valueOf(deHostId);
		} catch (NumberFormatException e) {
		}

		if (hostId < 1) {
			throw new ForbiddenException("enHostId 无法正常解析为可用的 hostId 数据ID，enHostId: " + enHostId);
		}

		// 通过 hostId 获取 host 数据
		Host host = hostServiceImpl.getInfoById(hostId);
		if (host == null) {
			// 给予一个403页面
			throw new ForbiddenException("未能获取 Host 数据！");
		}

		siteHolder.add(host);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		siteHolder.remove();
	}

}
